package com.chf.job.service.impl;

import com.chf.job.common.Const;
import com.chf.job.service.MailService;
import com.chf.job.utils.CookieUtil;
import com.chf.job.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Service
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String form;
    @Value("${spring.mail.password}")
    private String password;
    @Value("${spring.mail.host}")
    private String host;
    @Autowired
    private JavaMailSender javaMailSender;

    /**
     * 发送邮件
     *
     * @param email
     */
    @Override
    public void sendMail(String verifyCode, String email) {
        SimpleMailMessage mail = new SimpleMailMessage();
        // 由那个邮箱发出来
        mail.setFrom(form);
        // 发到那个邮箱去
        mail.setTo(email);
        // 抄送到邮箱
        mail.setBcc(form);
        // 设置标题
        mail.setSubject("这里存放的是一个标题信息");
        // 设置邮件内容
        mail.setText("您好！您的账号：" + email + "正在申请找回密码，验证码：" + verifyCode + ", 如果非本人操作请忽略！");

        // 发送邮件
        javaMailSender.send(mail);
    }

    /**
     * 发送激活服务邮件
     */
    public boolean sendActiveEmail(String email, HttpServletResponse response) {
        // 生成一个token验证邮件激活时间
        String emailToken = UUID.randomUUID().toString().replace("-", "");
        // 放在cookie中缓存MD5加密处理
        CookieUtil.addCookie(Const.ACTIVE_EMAIL_KEY, MD5Util.MD5EncodeUtf8(emailToken), response);
        String url = "http://localhost:8080/service/activeEmail.html?email=" + email + "&emailToken=" + emailToken;
        SimpleMailMessage mail = new SimpleMailMessage();
        // 由那个邮箱发出来
        mail.setFrom(form);
        // 发到那个邮箱去
        mail.setTo(email);
        // 抄送到邮箱
        mail.setBcc(form);
        // 设置标题
        mail.setSubject("开通招聘服务的邮件");
        // 设置邮件内容
        mail.setText("请将链接复制到浏览器中————————>>>>>" + url);
        // 发送邮件
        javaMailSender.send(mail);
        return true;
    }
}
